/**********************************************************
*
*   @file    useri2cReg.c
*   @author  Derrick Wang
*   @time    2018-4-26
*		@brief   i2c协议和外部交互的函数
*
*
***********************************************************/


#include "main.h"
#include "stm32f0xx_hal.h"
#include "userI2c.h"
#include "userI2cReg.h"
#include "nrf24l01.h"
#include "tim.h"
#include "iwdg.h"


struct userI2cRegStruct userI2cRegList[ALL_REG_NUMBER]=
{
	//通用寄存器
	{REG_CHECK,1,CMD_RT_TRANSMIT},
	{REG_TX_ADD,5,CMD_RT_RECEIVE},	
	{REG_RX_ADD,5,CMD_RT_RECEIVE},	
	{REG_TX_DATA,N,CMD_RT_RECEIVE},	
	{REG_RX_STATE,1,CMD_RT_TRANSMIT},
	{REG_RX_DATA,4,CMD_RT_TRANSMIT},
};

//获取要发送的数据，返回-1为错误，其他值为返回的数据长度
//cmd为命令，buf用来存放获取到的数据
uint8_t user_I2cGetTransmitData(uint8_t reg,uint8_t *buf)
{
	switch(reg)
	{
		case REG_CHECK:
			buf[0]=REG_CHECK_REPLY;
			break;
		case REG_RX_STATE:
			buf[0]=nrf24l01.getRxState();
			break;
		case REG_RX_DATA:
			nrf24l01.getRxData(4,buf);
			break;
	}
	return 1;
}
//命令执行函数
void user_I2cExecuteCallBack(uint8_t reg,uint8_t *buf,uint8_t size)
{
	switch(reg)
	{
		case REG_TX_ADD:
			if(size!=5)break;
			nrf24l01.setTxAdd(buf);
			break;
		case REG_RX_ADD:
			if(size!=5)break;
			nrf24l01.setRxAdd(buf);
			break;
		case REG_TX_DATA:
			nrf24l01.setTxData(buf,buf[5],buf+6);
			break;
	}
}

//10ms中断一次
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	static uint8_t i=0;
	if(htim==&htim17)
	{
		i++;
		if(i>=10)
		{
			i=0;
			HAL_IWDG_Refresh(&hiwdg);   //在一秒以内喂狗都可以
			user_I2cOverTimeCheck();			
		}
	}
}
